/* global document */
import React from 'react'
import PropTypes from 'prop-types'
import {config} from 'utils'
import {getToken} from 'utils/authority'
import {Button, Col, Form, Icon, Input, message, Row, Select, Upload} from 'antd'

const {Option} = Select
const {Search} = Input
const {api} = config

const ColProps = {
  xs: 24,
  sm: 12,
  style: {
    marginBottom: 16,
  },
}

const TwoColProps = {
  ...ColProps,
  xl: 96,
}

const Filter = ({
                  onAdd,
                  onFilterChange,
                  onResetPassword,
                  onResetRole,
                  filter,
                  form: {
                    getFieldDecorator,
                    getFieldsValue,
                    setFieldsValue,
                  },
                }) => {
  const handleFields = (fields) => {
    // const {createTime} = fields
    // if (createTime.length) {
    //   fields.createTime = [createTime[0].format('YYYY-MM-DD'), createTime[1].format('YYYY-MM-DD')]
    // }
    return fields
  }

  const valid = fields => {
    const {type, keyword} = fields

    if (!type && keyword) {
      message.warn("请选择查询类型")
      return false
    }

    return true
  }

  const handleSubmit = () => {
    let fields = getFieldsValue()
    if (!valid(fields)) {
      return
    }
    onFilterChange(fields)
  }

  const handleReset = () => {
    const fields = getFieldsValue()
    for (let item in fields) {
      if ({}.hasOwnProperty.call(fields, item)) {
        if (fields[item] instanceof Array) {
          fields[item] = []
        } else {
          fields[item] = undefined
        }
      }
    }
    setFieldsValue(fields)
    handleSubmit()
  }

  const handleChange = (key, values) => {
    let fields = getFieldsValue()
    fields[key] = values
    fields = handleFields(fields)
    onFilterChange(fields)
  }
  const {type, keyword} = filter

  const UploadProps = {
    name: 'excel',
    accept: '.csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel',
    action: `${api.importEmp}?Authentication=${getToken()}`,
    headers: {
      authorization: 'authorization-text',
    },
    onChange (info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 文件已经上传成功`)
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 文件上传失败`)
      }
    },
  }

  const prefixSelector = getFieldDecorator('type', {initialValue: type})(<Select placeholder="请选择" allowClear={true}
                                                                                 style={{width: 100}}>
    <Option value="LOGINUSER">登陆账户</Option>
    <Option value="REALNAME">员工姓名</Option>
    <Option value="PHONENUM">手机号码</Option>
    <Option value="DEPARTMENT">所属部门</Option>
    <Option value="ROLE">角色</Option>
  </Select>)

  return (
    <Row gutter={24}>
      <Col {...ColProps} xl={{span: 6}} md={{span: 8}}>
        {getFieldDecorator('keyword', {initialValue: keyword})(
          <Search addonBefore={prefixSelector}
                  style={{width: '100%'}}
                  placeholder="请输入"
                  onSearch={handleChange}
          />,
        )}
      </Col>
      <Col {...TwoColProps} xl={{span: 4}} md={{span: 24}} sm={{span: 24}}>
        <div style={{display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap'}}>
          <div>
            <Button type="primary" className="margin-right" onClick={handleSubmit}>查询</Button>
            <Button onClick={handleReset}>重置</Button>
          </div>
        </div>
      </Col>
      <Col {...TwoColProps} xl={{span: 12}} md={{span: 24}} sm={{span: 24}}>
        <div style={{display: 'flex', justifyContent: 'space-between', flexWrap: 'wrap'}}>
          <div>
            <Button className="margin-right" onClick={onResetPassword}>重置密码</Button>
            <Button className="margin-right" type="primary" onClick={onResetRole}>分配角色</Button>
            <a href={api.exportEmpTemp + "?Authentication=" + getToken()} target="_blank">
              <Button className="margin-right"><Icon type="cloud-download-o"/>下载导入模板</Button>
            </a>
            <a href={api.exportEmp + "?Authentication=" + getToken()} target="_blank">
              <Button className="margin-right"><Icon type="cloud-download-o"/>导出所有员工</Button>
            </a>
            <Upload {...UploadProps}>
              <Button>
                <Icon type="upload"/> 导入员工
              </Button>
            </Upload>
          </div>
        </div>
      </Col>
      <Col {...TwoColProps} xl={{span: 2}} md={{span: 24}} sm={{span: 24}}>
        <div className="flex-vertical-center" style={{float: 'right'}}>
          <Button type="ghost" onClick={onAdd}>新增员工</Button>
        </div>
      </Col>
    </Row>
  )
}

Filter.propTypes = {
  onAdd: PropTypes.func,
  form: PropTypes.object,
  filter: PropTypes.object,
  onFilterChange: PropTypes.func,
}

export default Form.create()(Filter)
